package com.tianyuan.lims.erp.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.json.FastJson;
import com.jfinal.upload.UploadFile;
import com.tianyuan.lims.common.annotation.NotNullValidate;
import com.tianyuan.lims.common.annotation.Permissions;
import com.tianyuan.lims.common.config.paragetter.BasePageRequest;
import com.tianyuan.lims.erp.admin.entity.AdminUser;
import com.tianyuan.lims.erp.admin.service.AdminFileService;
import com.tianyuan.lims.erp.admin.service.AdminUserService;
import com.tianyuan.lims.utils.BaseUtil;
import com.tianyuan.lims.utils.CommonCryptogramUtil;
import com.tianyuan.lims.utils.R;

/**
 * @author hmb
 */
public class AdminUserController extends Controller {

    @Inject
    private AdminUserService adminUserService;

    @Inject
    private AdminFileService adminFileService;

    /**
     * @param adminUser
     * @author hmb
     * 设置系统用户
     */
    @Permissions("manage:users:userSave")
    public void addUser(@Para("") AdminUser adminUser) {
        renderJson(adminUserService.setUser(adminUser, getPara("roleIds")));
    }

    @Permissions("manage:users:userUpdate")
    public void setUser(@Para("") AdminUser adminUser) {
        renderJson(adminUserService.setUser(adminUser, getPara("roleIds")));
    }

    /**
     * @author hmb
     * 更新状态
     */
    @Permissions("manage:users:userEnables")
    public void setUserStatus() {
        String ids = getPara("userIds");
        String status = getPara("status");
        renderJson(adminUserService.setUserStatus(ids, status));
    }

    /**
     * @param basePageRequest 分页对象
     * @author hmb
     * 查询系统用户列表
     */
    public void queryUserList(BasePageRequest<AdminUser> basePageRequest) {
        String roleId = getPara("roleId");
        renderJson(adminUserService.queryUserList(basePageRequest, roleId));
    }

    /**
     * @author hmb
     * 重置密码
     */
    @Permissions("manage:users:userEnables")
    public void resetPassword() {
        String ids = getPara("userIds");
        String pwd = getPara("password");
        renderJson(adminUserService.resetPassword(ids, pwd));
    }

    /**
     * @author hmb
     * 查询上级列表
     */
    @Permissions("manage:users:read")
    public void querySuperior() {
        String realName = getPara("realName");
        renderJson(adminUserService.querySuperior(realName));
    }

    /**
     * 查询所用用户列表
     *
     * @author hmb
     */
    @Permissions("manage:users:read")
    public void queryAllUserList() {
        renderJson(adminUserService.queryAllUserList());
    }

    /**
     * @author zxy
     * 查询系统所有用户名称
     */
    public void queryListName(@Para("search") String search) {
        renderJson(adminUserService.queryListName(search));
    }

    /**
     * @author zxy
     * 查询部门属用户列表
     */
    public void queryListNameByDept(@Para("name") String name) {
        renderJson(adminUserService.queryListNameByDept(name));
    }

    /**
     * 查询当前登录的用户
     *
     * @author zhangzhiwei
     */
    public void queryLoginUser() {
        renderJson(R.ok().put("data", adminUserService.resetUser(getRequest())));
    }

    public void updateImg() {
        String prefix = BaseUtil.getDate();
        UploadFile uploadFile = getFile("file", prefix);
        R r = adminFileService.upload(uploadFile, null, "file", "/" + prefix, getRequest());
        if (r.isSuccess()) {
            String url = (String) r.get("url");
            if (adminUserService.updateImg(url, getParaToLong("userId"))) {
                renderJson(R.ok());
                return;
            }
        }
        renderJson(R.error("修改头像失败"));
    }

    public void updatePassword(@Para String oldPwd, @Para String newPwd) {
        if (StrUtil.isEmpty(oldPwd) || StrUtil.isEmpty(newPwd)) {
            if (StrUtil.isEmpty(getRawData())) {
                renderJson(R.error("参数！"));
                return;
            }
            java.util.Map<String, Object> args = FastJson.getJson().parse(getRawData(), java.util.Map.class);
            if (args.get("oldPwd") != null) oldPwd = args.get("oldPwd").toString();
            if (args.get("newPwd") != null) newPwd = args.get("newPwd").toString();
            if (StrUtil.isEmpty(oldPwd) || StrUtil.isEmpty(newPwd)) {
                renderJson(R.error("请输入用户名和密码！"));
                return;
            }
        }

        AdminUser adminUser = BaseUtil.getUser();

        adminUser = AdminUser.dao.find("select * from crm_admin_user where user_id = ? ", adminUser.getUserId()).get(0);
        oldPwd = CommonCryptogramUtil.doSm2Decrypt(oldPwd);
        newPwd = CommonCryptogramUtil.doSm2Decrypt(newPwd);
        if (!BaseUtil.verify(adminUser.getUsername() + oldPwd, adminUser.getSalt() == null ? "" : adminUser.getSalt(), adminUser.getPassword())) {
            renderJson(R.error("密码输入错误"));
            return;
        }
        adminUser.setPassword(newPwd);
        boolean b = adminUserService.updateUser(adminUser);
        if (b) {
            //BaseUtil.userExit(adminUser.getUserId(), null);
            setSessionAttr("user", null);
            setSessionAttr("token", "");
        }
        renderJson(R.isSuccess(b));
    }

    @NotNullValidate(value = "realname", message = "姓名不能为空")
    @NotNullValidate(value = "username", message = "用户名不能为空")
    public void updateUser(@Para("") AdminUser adminUser) {
        boolean b = adminUserService.updateUser(adminUser);
        renderJson(R.isSuccess(b, "修改信息失败"));
    }

    /**
     * @param id       用户ID
     * @param username 用户新账号
     * @param password 用户新密码
     * @author zhangzhiwei
     */
    @Permissions("manage:users:userUpdate")
    @NotNullValidate(value = "username", message = "账号不能为空")
    @NotNullValidate(value = "password", message = "密码不能为空")
    @NotNullValidate("id")
    public void usernameEdit(@Para("id") Integer id, @Para("username") String username, @Para("password") String password) {
        renderJson(adminUserService.usernameEdit(id, username, password));

    }

    public void queryUserByDeptId(@Para("deptId") Integer deptId) {
        renderJson(R.ok().put("data", adminUserService.queryAllUserByDeptId(deptId)));
    }
}
